package com.by.gateway.controller;

import com.by.gateway.config.GatewayChannelInitializer;
import com.by.gateway.service.GatewayForwardService;
import com.by.gateway.service.EndpointService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import jakarta.annotation.PreDestroy;

@Slf4j
@Component
public class NettyGatewayServer implements CommandLineRunner {

    // BossGroup：负责接受连接
    private final EventLoopGroup bossGroup = new NioEventLoopGroup();
    // WorkerGroup：负责处理读写事件
    private final EventLoopGroup workerGroup = new NioEventLoopGroup();

    @Value("${gateway.port:8080}")
    private int port;

    @Autowired
    private GatewayForwardService gatewayForwardService;


    @Override
    public void run(String... args) throws Exception {
        startNettyServer();
    }

    private void startNettyServer() {
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new GatewayChannelInitializer(gatewayForwardService))
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            log.info("Starting Netty gateway on port {}", port);
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("Netty server interrupted", e);
            Thread.currentThread().interrupt();
        } finally {
            shutdown();
        }
    }

    @PreDestroy
    public void shutdown() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        log.info("Netty gateway server shut down gracefully.");
    }
}